package cn.darkhorse.common.report.service.impl;

import cn.darkhorse.common.report.service.QRCodeService;
import cn.darkhorse.common.util.ConvertToMultipartFile;
import cn.darkhorse.common.util.QRCodeUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Service
public class QRCodeServiceImpl implements QRCodeService {
    /**
     * 二维码上传服务器  且返回路径
     * @param bufferedImage
     * @return
     */
    @Override
    public String uploadServer(BufferedImage bufferedImage)
    {
        //将BufferedImage 转换为 MultipartFile 进行文件上传
        try
        {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage,"jpg",out);
            byte[] imageByte = out.toByteArray();
            MultipartFile file = new ConvertToMultipartFile(imageByte, IdUtils.simpleUUID(), IdUtils.fastSimpleUUID(), MimeTypeUtils.IMAGE_JPG,imageByte.length);
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath()+"/QRCode";
            // 上传并返回新文件名称
            //file.getContentType() image/jpg
            String fileName = FileUploadUtils.upload(filePath, file);
            return fileName;
        }
        catch (IOException e)
        {
            throw  new ServiceException("二维码创建失败,请联系管理员");
        }
    }
    /**
     * 创建二维码
     * @return  二维码上传之后返回的Url
     */
    @Override
    public String createQRImage(String charset, String content, Integer width, Integer height, String desperation, Integer step)
    {
        if(StringUtils.isBlank(charset)){
            charset="UTF-8";
        }
        if(null==width){
            width=400;
        }
        if (null==height){
            height=400;
        }
        if (null==step){
            step=1;
        }
        BufferedImage bufferedImage = QRCodeUtil.createImage(charset, content, width, height);
        QRCodeUtil.addBottomFont(bufferedImage,desperation,step);
        //上传服务器
        return uploadServer(bufferedImage);
    }

    /**
     * 创建二维码
     *
     * @param content
     * @param desperation
     * @return 二维码上传之后返回的Url
     */
    @Override
    public String createQRImage(String content, String desperation) {
        return createQRImage(null,content,null,null,desperation,null);
    }


}
